package com.scalar.forecast.systemprefs.actioncommands;

import com.scalar.ScalarException;
import com.scalar.forecast.actionCommands.ActionCommand;
import com.scalar.forecast.commons.SessionKeys;
import com.scalar.forecast.commons.logger.Logger;
import com.scalar.forecast.commons.logger.LoggerManager;
import com.scalar.forecast.systemprefs.SystemPreferences;
import com.scalar.forecast.systemprefs.SystemPreferencesSingleton;
import com.scalar.forecast.systemprefs.dao.SystemPrefsDAO;
import com.scalar.forecast.utils.CommonUtils;
import com.scalar.forecast.forecastSetup.dao.ForecastSetupDAO;

import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.users.User;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 *  @author Basha
 *  @version 1.0
 */

public class SystemPreferencesSaveCommand extends ActionCommand
{
    private static final Logger LOGGER = LoggerManager.getLogger( SystemPreferencesSaveCommand.class );

   /**
     * Execute the SystemPreferencesSaveCommand
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @throws com.scalar.ScalarException
     */


    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response ) throws ScalarException
    {
        //System.out.println("SystemPreferencesSaveCommand");

        HashMap errors = new HashMap();
        HashMap info =  new HashMap();

        ActionForward actionForward = mapping.findForward( "preferences_system" );

        DBTransaction dbTransaction = null;
        HttpSession  session = request.getSession();
        boolean success = false;
        String userId = ( ( User )session.getAttribute( SessionKeys.USER_KEY ) ).getUserId();
        com.scalar.forecast.systemprefs.forms.SystemPreferencesForm systemPreferencesForm = ( com.scalar.forecast.systemprefs.forms.SystemPreferencesForm ) form;
        SystemPreferences systemPreferences= systemPreferencesForm.getSystemPreferences();

        try
        {
            LOGGER.log(Logger.DEBUG, "In System SavePreferences Command" );
            dbTransaction = DBTransaction.getInstance();
            dbTransaction.begin();

            //saving the systemPreferences information
            SystemPrefsDAO.saveSystemPeferences( dbTransaction, systemPreferences, userId );
            SystemPreferencesSingleton.update();
            //saving forecast timeframe details
            ForecastSetupDAO.updateForecastTimeFrame( systemPreferencesForm.getForecastTimeFrame(), dbTransaction );
            success = true;
            LOGGER.log(Logger.DEBUG, "SystemPreferences  Saved Successfully" );
        }
        catch( Exception e )
        {
            LOGGER.log( Logger.ERROR, "Error while saving SystemPreferences", e );
        }
        finally
        {
            if( dbTransaction != null )
            {
                if( success )
                {
                    try
                    {
                        dbTransaction.commit();
                    }
                    catch( Exception e )
                    {
                        LOGGER.log( Logger.DEBUG, "Error while commiting the saveSystemPreferences", e );
                        throw new ScalarException( "Error while commiting the saveSystemPreferences", e );
                    }
                }
                else
                {
                    try
                    {
                        dbTransaction.rollback();
                    }
                    catch( Exception e )
                    {
                        LOGGER.log( Logger.DEBUG, "Error while rolling back the saveSystemPreferences", e );
                        throw new ScalarException( "Error while rolling back the saveSystemPreferences", e );
                    }
                }
            }
        }
        if ( success )
        {


            info.put("System Preferences  saved successfully",null);

            if (!info.isEmpty()){
                request.setAttribute ( SessionKeys.INFO_MESSAGES, info );
            }



            //System.out.println("SAVED SUCCESSFULLY");
            actionForward = mapping.findForward( "success_preferences" );
            //actionForward = mapping.findForward( "preferences_system" );
        }
        else
        {
            LOGGER.log( Logger.DEBUG, "Error while saving the System Preferences  forwarding to the system preferences page" );

            // setting the request attributes for default creation and searching of documents

            // setting the request attributes
            request.setAttribute( "buildMasterCantOverrideSFC" , CommonUtils.getCanBuildMasterOverrideSalesForecast() );
            request.setAttribute( "partNumberTypes" , CommonUtils.getPartNumberTypes() );
            request.setAttribute( "priceTypes" , CommonUtils.getPriceTypes() );


            errors.put("Error while saving the System Preferences  forwarding to the system preferences page",null);

            if ( !errors.isEmpty () ) {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            }


            actionForward = mapping.findForward( "preferences_system" );
        }

        return actionForward;
    }
}
